<?php

namespace XXXX\PlatformBundle\Util;

use Doctrine\ORM\EntityManager;

use XXXX\PlatformBundle\Entity\Base\User;

/**
 * In case student has both type of product: adult and primary, choose "role" for session  lifetime.
 *
 * @author Ryszard Ratajczak <rratajczak@xxxx.com.pl>
 */
class SessionRoleSelector
{
    /**
     * EntityManager
     *
     * @var EntityManager $em - entity manager
     */
    private $em;

    /**
     * EntityManager
     *
     * @var EntityManager $contentEm - entity manager
     */
    private $contentEm;

    /**
     * Set EntityManager
     *
     * @param EntityManager $em        - entity manager
     * @param EntityManager $contentEm - content entity manager
     */
    public function __construct(EntityManager $em, EntityManager $contentEm)
    {
        $this->em = $em;
        $this->contentEm = $contentEm;
    }

    /**
     * let a Student to choose a role for session lifetime
     * we accspect true for Primary, false for Adult and null for a student with both kinds of products
     *
     * @param User $user - object user
     *
     * @return [bool|null]
     */
    public function isPrimary(User $user)
    {
        $productRepository = $this->contentEm->getRepository('XXXXPlatformBundle:Content\Product');

        $products = $productRepository->getProducts($this->em, $user);

        $hasPrimary = false;
        $hasNonPrimary = false;

        foreach ($products as $product) {
            if ($product->getIsPrimary()) {
                $hasPrimary = true;
            } else {
                $hasNonPrimary = true;
            }
        }

        if ($hasPrimary && $hasNonPrimary) {

            return null;
        } else if ($hasPrimary) {

            return true;
        } else {

            return false;
        }
    }
}
